package xiang.weiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xiang.weiyu.common.CustomException;
import xiang.weiyu.mapper.CategoryMapper;
import xiang.weiyu.pojo.Category;
import xiang.weiyu.pojo.Dish;
import xiang.weiyu.pojo.Setmeal;
import xiang.weiyu.service.CategoryService;
import xiang.weiyu.service.DishService;
import xiang.weiyu.service.SetmealService;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 该方法重写了MP提供的remove方法
     * 根据id删除分类,删除之前还需要判断该菜品分类是否有相关联的其他数据表
     *
     * @param id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        //1.查询当前分类是否关联了菜品数据表<Dish>,如果已关联,抛出异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //1.1查询表Dish的字段categoryId是否含有与传入的id相同
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        if (count1 > 0) {
            //已经关联了菜品,抛出异常
            throw new CustomException("当前分类关联了菜品，无法删除");
        }
        //2.查询当前分类是否关联了套餐数据表<setmeal>,如果已关联,抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.1查询表setmeal的字段categoryId是否含有与传入的id相同
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2 > 0) {
            //已经关联了菜品,抛出异常
            throw new CustomException("当前分类关联了套餐，无法删除");
        }
        //3.都没有关联,正常删除该条菜品分类数据,调用Mp提供的remove方法
        super.removeById(id);
    }
}
